import os
from PIL import Image

def crop_image(input_path, crop_area, output_path, filename):
    image = Image.open(input_path)
    x, y, width, height = crop_area
    cropped_image = image.crop((x, y, x + width, y + height))
    cropped_filename = os.path.join(output_path, f"cropped_{filename}")
    cropped_image.save(cropped_filename)

def rotate_image(input_path, angle, output_path, filename):
    image = Image.open(input_path)
    rotated_image = image.rotate(-angle)  # Pillow旋转是逆时针，所以用负号转为顺时针
    rotated_filename = os.path.join(output_path, f"rotated_{filename}")
    rotated_image.save(rotated_filename)
    return rotated_filename  # 返回旋转后的文件路径以用于裁剪

def batch_process_images(folder_path, output_path, crop_area, angle):
    # 确保输出文件夹存在
    cropped_path = os.path.join(output_path, 'cropped')
    rotated_path = os.path.join(output_path, 'rotated')
    
    if not os.path.exists(cropped_path):
        os.makedirs(cropped_path)
    if not os.path.exists(rotated_path):
        os.makedirs(rotated_path)

    for filename in os.listdir(folder_path):
        if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif')):
            input_path = os.path.join(folder_path, filename)
            # 旋转并返回旋转后的文件路径
            rotated_file_path = rotate_image(input_path, angle, rotated_path, filename)
            # 使用旋转后的文件路径进行裁剪
            crop_image(rotated_file_path, crop_area, cropped_path, filename)
            print(f'Processed {filename}')

if __name__ == '__main__':
    output_path = r'C:\Users\Umbra\Desktop\paper\video-fps'
    folder_path = r'C:\Users\Umbra\Desktop\paper\video-fps\origin'
    crop_area = (70, 90, 764, 478)  # 裁剪区域(X, Y, Width, Height)
    angle = 0  # 旋转角度
    batch_process_images(folder_path, output_path, crop_area, angle)
